package handler

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-mnger/cache"
	"novel-mnger/model"
	"novel-mnger/pck"
	"strconv"
	"time"
)

func Login(c *gin.Context) {

	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{"code": 500, "msg": "为空"})
		return
	}
	redis_key := "login_error+" + username
	errCout, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCout >= 3 {
		c.JSON(200, gin.H{"code": 500, "msg": "禁止登录"})
		return
	}
	var data model.User
	err := model.DB.Where("username=?", username).Debug().First(&data).Error
	if err != nil {
		c.JSON(200, gin.H{"code": 500, "msg": "查询失败"})
		return
	}
	if data.ID == 0 {
		c.JSON(200, gin.H{"code": 500, "msg": "用户不存在"})
		return
	}
	if data.Password != pck.Md5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCout == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Minute*40)
			c.JSON(200, gin.H{"code": 500, "msg": "密码错误3次，禁止40分钟登录"})
			return
		} else {
			c.JSON(200, gin.H{"code": 500, "msg": "密码错误"})
			return
		}
	}
	c.JSON(200, gin.H{"code": 200, "msg": "登录成功", "user": data})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var users []model.User
	redis_key := "user_page_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Debug().Find(&users)
		jsonData, _ := json.Marshal(users)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &users)
	}
	var total int64
	model.DB.Model(&model.User{}).Count(&total)
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "user": users, "total": total})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	var users model.User
	redis_key := "user_id_" + id
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&users)
		jsonData, _ := json.Marshal(users)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &users)
	}
	c.JSON(200, gin.H{"code": 200, "msg": "查询成功", "user": users})
	return
}
